import React, {useContext, useEffect, useState} from 'react';
import {
    ActivityIndicator,
    Alert, Button,
    Dimensions,
    ImageBackground,
    Modal,
    PermissionsAndroid,
    Platform,
    RefreshControl,
    ScrollView,
    StyleSheet,
    TouchableOpacity,
    View,
} from 'react-native';
import {Avatar, Icon, ListItem, TabView, Text} from 'react-native-elements';
import {useFocusEffect} from '@react-navigation/native';
import {
    getAllZhiYaHeYue,
    getBestNode,
    getCurrentHeight,
    getHotTokens,
    getMyZhiYaHeYue,
    GetRedEnvelope,
    getTokenBalance,
    getVersion,
    nodes,
    QueryRedEnvelope
} from "./../libs/nodes";
import {constansts} from "./../libs/constansts";
import LocaleContext from '../libs/locale';
import WalletContext from '../libs/wallet';
import {formartMoney} from '../libs/helpers';
import {getBalances} from '../libs/nodes';
import scan from '../assets/Assets/scan.png';
import balanceBG from '../assets/Assets/balance_bg.png';
import send from '../assets/Assets/send.png';
import receive from '../assets/Assets/receive.png';
import txs from '../assets/Assets/txs.png';
import logo from '../assets/logo.png';
import NFT from '../assets/Assets/NFT.png';
import copyImg from "../assets/Assets/copy.png";


import AsyncStorage from '@react-native-async-storage/async-storage';
import RNFetchBlob from 'rn-fetch-blob'
// import RNFS from 'react-native-fs'
import RNApkInstallerN from 'react-native-apk-installer-n';
import {ProgressBar} from '@react-native-community/progress-bar-android';
import Toast from "react-native-simple-toast";
import Clipboard from "@react-native-community/clipboard";
import RedEnvelopeLoad from "./RedEnvelopeLoad";
import WebBrowser from "../components/WebComponentP";
import {addRedEnvelopeGet, getRedEnvelopeGet,} from "../libs/pendingTxs";
import Sound from "react-native-sound";
import {Tab} from "react-native-elements/dist/tab/Tab";
import {Image} from "react-native-elements/dist/image/Image";
import {getMyAddNFTContractsDetail, getMyNFTSByContract, modifyMyAddNFTS, NFTView_TitleSize} from "../libs/NFTView";
import SmartXLogo from "../assets/NFT/SmartXNFT.png";
// import ProgressBar from "../components//progress.tsx";

// import ProgressBar from "../components/processbar/ProgressBar";
// import { showProgressBar } from "./Upload";
// import ProgressBar from "../components/processbar/progress";


const {width,height,scale} = Dimensions.get("window");
// console.log("屏幕="+width+" "+height+" "+scale);

const Home = ({ navigation }: any) => {
  const locale:any = useContext(LocaleContext);
  const wallet: any = useContext(WalletContext);
  const [balances, setBalances] = useState({ SAT: "", tokens: [] });
  const [refresh, setRefresh] = useState(true);
  const [lang, setLang] = useState("zh");
  const [storagePermission, setStoragePermission] = useState(false);

  const [modalVisible, setModalVisible] = useState(false);
  const [progressNumber, setProgressNumber] = useState(0);
  const [SATprice, setSATPrice] = useState("0.00");
  const [HYSAT, setHYSAT] = useState("0.00");
  const [AllSAT, setAllSAT] = useState("0.00");
  const [AllSATPrice, setAllSATPrice] = useState("0.00");
  const [showGift,setShowGift] = useState(false);
  const [Gifturl,setGifturl]=useState('http://192.168.1.104:8181/#/active');

  const [promptUpdate, setPromptUpdate] = useState(false);
  //添加进代币的内容
  const [openRedEnvelopeConAddress,setOpenRedEnvelopeConAddress] = useState('');
  const [openRedEnvelopeTokenName,setOpenRedEnvelopeTokenName] = useState('');
  const [openRedEnvelopeUrl,setOpenRedEnvelopeUrl] = useState('');

  //测试红包领取页面
  const [showRedEnvelopeLoad,setShowRedEnvelopeLoad] = useState(false);
  const [pkgid,setPkgid] = useState("");
  const [coverTxt,setCoverTxt] = useState("");
  const [sender,setSender] = useState(true)//红包的发送人
  const [loadType,setLoadType] = useState('0');
  //公告内容
  const [Announce,setAnnounce] = useState([""]);
  const pkg = require('../package.json');
  //新增NFT和资产选择
  const [Asset_Index,setAsset_Index] = useState(0);
  const [NFTContracts,setNFTContracts]:any = useState([]);
    //获取设置一些全局变量
    useEffect(()=> {
        const getChatAttr = async () => {
            let Asset_HYSAT = await AsyncStorage.getItem("Asset_HYSAT") ;
            if (Asset_HYSAT != null) {
                setHYSAT(Asset_HYSAT);
            }
            let chatSearchFrequency = await AsyncStorage.getItem("chatSearchFrequency") ;
            let chatSearchMaxLength = await AsyncStorage.getItem("chatSearchMaxLength");
            let chatSearchMaxTime = await AsyncStorage.getItem("chatSearchMaxTime");
            let chatCustomer = await AsyncStorage.getItem("chatCustomer");
            let chatViewStats = await AsyncStorage.getItem("chatViewStats");
            let chatGetAllMaxLength = await AsyncStorage.getItem("chatGetAllMaxLength");
            // console.log(`chatCustomer:${chatCustomer}`)
            if (chatSearchMaxTime != null) {
                constansts.chatSearchMaxTime = parseInt(chatSearchMaxTime);
            }
            if (chatSearchMaxLength != null) {
                constansts.chatSearchMaxLength = parseInt(chatSearchMaxLength);
            }
            if (chatSearchFrequency != null) {
                constansts.chatSearchFrequency = parseInt(chatSearchFrequency);
                constansts.refreshTime = constansts.chatSearchFrequency;
            }
            if (chatCustomer == "false") {
                constansts.chatCustomer = false;
            }
            else
            {
                constansts.chatCustomer = true;
            }
            if (chatViewStats == "false") {
                constansts.chatViewStats = false;
            }
            if(chatGetAllMaxLength != null){
                constansts.chatGetAllMaxLength = parseInt(chatGetAllMaxLength);
            }
        }
        getChatAttr();
    },[])

    //初始化默认代币和主币内容
    useEffect(()=>{
        const Init = async () => {
            console.log("初始化默认代币和主币内容")
            //初始化全部SAT余额
            let Asset_AllSAT:any = await AsyncStorage.getItem("Asset_AllSAT");
            setAllSAT(formartMoney(Asset_AllSAT,4));
            //初始化主币余额
            let Asset_SATcount:any = await AsyncStorage.getItem("Asset_SATcount");
            if (Asset_SATcount != null) {
                constansts.SATcount = Asset_SATcount;
            }
            //已添加的热门tokens
            var tokens = await AsyncStorage.getItem('@addTokens');
            if (tokens)
                constansts.addTokens = (JSON.parse(tokens));
            else
                constansts.addTokens = [];
            let balancaTemp:any = balances;
            balancaTemp.SAT = Asset_SATcount;
            balancaTemp.tokens = constansts.addTokens;
            constansts.Balance = balancaTemp;

            constansts.Balance.tokens.sort((a:any,b:any)=>{
                let res =  Number(a.DollarPrice) < Number(b.DollarPrice) ;
                if(Number(b.DollarPrice) > 0 || Number(a.DollarPrice) > 0)
                {
                    return res;
                }
                else
                {
                    res = Number(a.balance) < Number(b.balance);
                    return res
                }
            })
            setBalances(balancaTemp)
        }
        Init();
    },[])

    //初始化函数
    useEffect(() => {
        const work = async () => {
            if (!refresh) {
                return;
            }
            console.log("初始化函数")
            setRefresh(false);
            setShowGift(false);
            try{
                constansts.tran_url = await AsyncStorage.getItem('constansts_tran_url');
                if(constansts.tran_url === "")
                {
                    constansts.tran_url = await getBestNode();;
                }
            }
            catch (e) {

            }
            try {
                // 获取热门代币
                try {
                    const ht = await getHotTokens();
                    var hotTokens = JSON.parse(JSON.stringify(ht));
                    if (hotTokens.res_info == "OK") {
                        constansts.HotTokens = hotTokens.tokens;
                    }
                }catch (e) {
                    console.log("初始化函数：getHotTokensError==>"+e);
                }
                const balances = await getBalances(wallet.address);
                constansts.SATcount = balances.SAT;
                await AsyncStorage.setItem("Asset_SATcount",(balances.SAT).toString())
                //清除流动性代币
                for (var i = 0; i < balances.tokens.length;) {
                    if (balances.tokens[i].name == "PFP") {
                        balances.tokens.splice(i, 1);
                        continue;
                    }
                    i++;
                }
                //添加热门tokens
                const tokens = await AsyncStorage.getItem('@addTokens');
                if (tokens)
                    constansts.addTokens = (JSON.parse(tokens));
                else
                    constansts.addTokens = [];
                //刷新代币图标
                for(let i = 0 ; i < constansts.addTokens.length ; i++)
                {
                    for( let ii = 0 ; ii < constansts.HotTokens.length ; ii++)
                    {
                        if(constansts.addTokens[i].address === constansts.HotTokens[ii].address)
                        {
                            constansts.addTokens[i].url = constansts.HotTokens[ii].url;
                        }
                    }
                }
                // 添加的代币显示
                balances.tokens = constansts.addTokens;

                //补上对应的余额
                for (var i = 0; i < balances.tokens.length; i++) {
                    var amount = await getTokenBalance(wallet.address as string, balances.tokens[i].address);
                    balances.tokens[i].balance = (amount as any).amount;
                    constansts.addTokens[i].balance = (amount as any).amount;
                }
                await AsyncStorage.setItem('@addTokens',JSON.stringify(constansts.addTokens));
                //将代币中有余额的数据放入交易选择代币列表中
                const SAT = [{name: 'SAT', balance: balances.SAT}];
                (constansts.trantokens as any) = SAT;
                for (var i = 0; i < balances.tokens.length; i++) {
                    if ((balances.tokens[i]).balance > 0)
                        (constansts.trantokens as any).push(balances.tokens[i]);
                }

                //获取显示的币种
                constansts.tokens = balances.tokens;
                constansts.Balance =balances;
                // console.log("Asset SetBalance")
                // setBalances(balances);
                getSATPrice();
                poolCacheWork();
            } catch (e) {
                console.log('初始化函数：getBalances:', e);
            }
        };
        work()
    }, [refresh]);

    //初始化NFT的合约
    useEffect(()=>{
        const getNFTList = async () => {
            console.log("初始化NFT的合约")
            // const addressTemp = "gtXacD7NCxW3tLbGg3oW33DQKEx4wQmh6";
            const addressTemp = wallet.address;
            // //先获取地址有哪些NFT合约和余额，这边应该是先不显示，然后添加进入的
            let contractList = await getMyAddNFTContractsDetail(addressTemp)
            // console.log(contractList[0].myNFTS.length)
            setNFTContracts(contractList);
        }
        getNFTList();
    },[refresh])

    //缓存矿池数据
    const poolCacheWork = async ()=>{
        console.log('缓存矿池数据')
        try {
            const lang = await AsyncStorage.getItem('@lang');

            setGifturl("http://192.168.1.104:8181/#/active?lang="+lang);
            setLang(lang as any);
            const infoAll = await getAllZhiYaHeYue();
            const currentHeight = await getCurrentHeight();
            let arr = [];
            for (var i in infoAll) {
                if (infoAll[i].Contract && parseInt(infoAll[i].LBH)>(parseInt(currentHeight)-120)) {
                    infoAll[i].status = "20";
                    arr.push(infoAll[i])
                }
            }
            arr.sort(compareAll("Contract"));
            const infoMy = await getMyZhiYaHeYue(wallet.address);
            // const info = JSON.parse(infoMy);
            let hyMyArr = [];
            let onLineListTempt = [];
            var HYSAT = 0;
            for (var i in infoMy) {
                HYSAT+=parseFloat(JSON.parse(infoMy[i])[5])/parseFloat(JSON.parse(infoMy[i])[6])*parseFloat(JSON.parse(infoMy[i])[3]);
                if (JSON.parse(infoMy[i])[7]) {
                    for (var allP in arr) {
                        if (JSON.parse(infoMy[i])[0] == arr[allP].Contract) {
                            onLineListTempt.push(JSON.parse(infoMy[i]));
                        }
                    }
                    JSON.parse(infoMy[i])[8]="20";
                    hyMyArr.push(infoMy[i])
                }
            }
            hyMyArr.sort(compareMy(0));
            (constansts.poolMyList as any) = hyMyArr;
            (constansts.onLineListTempt as any) = onLineListTempt;
            arr=sortAll(arr);
            (constansts.poolAllList as any) = arr; //这个地方有点bug会清除数据

            //先写上数据然后获取价格然后再去计算
            setHYSAT(formartMoney(HYSAT.toString(),4));
            await AsyncStorage.setItem("Asset_HYSAT",formartMoney(HYSAT.toString(),4));
            var allSAT=HYSAT+parseFloat(constansts.SATcount);
            await AsyncStorage.setItem("Asset_AllSAT",formartMoney(allSAT.toString(),4));
            setAllSAT(formartMoney(allSAT.toString(),4));
            var AllSatMoney = 0;
            //获取价格
            const ht = await getHotTokens();
            const p = ht.dict;
            const price = parseFloat(p.satprice);
            const usdtPrice =parseFloat(p.usdtprice);
            if(lang=="zh")
                AllSatMoney = allSAT*price;
            else
                AllSatMoney = allSAT*usdtPrice;

            setAllSATPrice(formartMoney(AllSatMoney.toString(),4));
        }catch (e) {
            console.log("缓存矿池数据：Error"+e)
        }
    };

    const setTxsNull = async () => {
        var txs: any[] = [];
        await AsyncStorage.setItem('@wallet_address', wallet.address)//初始化使用地址
        // await AsyncStorage.setItem('@txs', JSON.stringify(txs));//清空未完成交易数据
        //添加页面返回监听
        navigation.addListener('focus', () => {
            setRefresh(true);
        });
    }

    const compareAll = (prop:any)=>  {
        return function (obj1:any, obj2:any) {
            var val1 = obj1[prop].toLowerCase();
            var val2 = obj2[prop].toLowerCase();
            if (val1 < val2) {
                return -1;
            } else if (val1 > val2) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    const compareMy = (prop:any)=>  {
        return function (obj1:any, obj2:any) {

            obj1 = JSON.parse(obj1);
            obj2 = JSON.parse(obj2);
            var val1 = obj1[prop].toLowerCase();
            var val2 = obj2[prop].toLowerCase();
            if (val1 < val2) {
                return -1;
            } else if (val1 > val2) {
                return 1;
            } else {
                return 0;
            }
        }

    }

    const sortAll = (prop:any) => {
        var arr=[];
        for(var i=0;i<constansts.contractListInfo.length;i++)
        {
            for(var ii=0;ii<prop.length;ii++)
            {
                if(prop[ii].Contract==constansts.contractListInfo[i])
                {
                    arr.push(prop[ii]);
                }
            }
        }
        for(var i=0;i<prop.length;i++)
        {
            (constansts.contractListInfo as any).indexOf(prop[i][0])!==-1?
            arr.push(prop[i]):null;
        }
        return arr;
    }

    //监听剪切板
    const work2 = async () => {
        const ClipboardString = await getClipboardString();
        if (ClipboardString == "") {
            return;
        }
        var RedEnvelopeReceivedList = await getRedEnvelopeGet();

        if (ClipboardString == "") {
            return;
        }
        var password ="";
        if(ClipboardString.indexOf("(")!==-1&&ClipboardString.indexOf(")")!==-1)
        {
            password = ClipboardString.slice(ClipboardString.indexOf("(")+1,ClipboardString.indexOf(")"));
        }
        else
        {
            password=ClipboardString;
        }
        if (RedEnvelopeReceivedList.indexOf(password) !== -1 || password.length!==15) {
            return;
        }

        try {
            var result: any = await QueryRedEnvelope(password);
            var sender = result.dict.nickname || result.dict.sender;
            setOpenRedEnvelopeConAddress (result.dict.type || "");
            setOpenRedEnvelopeTokenName(result.dict.coinname || "");
            setOpenRedEnvelopeUrl ( result.dict.url || "");
            setCoverTxt(result.dict.desc);
            if (sender !== "") {
                await addRedEnvelopeGet(password);
                setPkgid(password);
                setSender(sender);
                var temp = 0;//0是红包还有可以强，并且没抢过这个红包。   1是抢过这个红包了。   2是红包没了，手速慢了
                if (result.pkgitems.length < parseInt(result.dict.number))//红包还有，里面区分0和1
                {
                    if (result.pkgitems.length != 0) {
                        for (var i = 0; i < result.pkgitems.length; i++) {
                            if (result.pkgitems[i].getter == wallet.address) {
                                temp = 1;
                                break;
                            }
                        }
                    } else {
                        temp = 0;
                    }

                } else if (result.pkgitems.length >= parseInt(result.dict.number)) //红包没了 ，里面区分抢过了1和没抢过2
                {
                    if (result.pkgitems.length != 0) {
                        for (var i = 0; i < result.pkgitems.length; i++) {
                            if (result.pkgitems[i].getter == wallet.address) {
                                temp = 1;
                                break;
                            }
                            if (i == result.pkgitems.length - 1) {
                                temp = 2;
                            }
                        }
                    } else {
                        temp = 2;
                    }
                } else {
                    temp = 0;
                }
                if (temp == 1) {
                    Toast.show("该红包您已经抢过了")
                    navigation.navigate('RedEnvelopeInfo', {pkgid: password});
                } else {
                    setLoadType(temp.toString())
                    setShowRedEnvelopeLoad(true);
                }

            } else {
                // Alert.alert("", "没有此口令。");
            }
        } catch (e) {
            console.log("抢红包错误==》" + e)
            return;
        }

    }

    useFocusEffect(
        React.useCallback(() => {
            console.log("FocusOnAsset");
            work2();
            // getSATPrice();
            const setAnn = () => {
                var Ann = ["刘锋林","在这里","写公告","注意了","最后一个了"];
                setAnnounce(Ann);
            }
            return ()=> {
                setAnn();
            };
        }, [])
    );

    //添加页面监听 修改版本代币如果要修改记得这里
    useEffect(() => {
        const work = async () => {
            const time = await AsyncStorage.getItem('@isFirstTime');//确认第一次登录
            if(time && parseInt(time)===3)
            {}
            else
            {
                await AsyncStorage.setItem('@isFirstTime', "3");
                await AsyncStorage.setItem('@addTokens', "[]");
            }

        }
        const setAnn = () => {
            var Ann = ["刘锋林","在这里","写公告","注意了","最后一个了"];
            setAnnounce(Ann);
            console.log(`公告内容是：${JSON.stringify(Announce)}`)
        }

        if (constansts.isStart == 0) {
            constansts.isStart = 1;
            setTxsNull();
            setAnn();
        }

        work();
    },[])

    //TODO Android6.0+获取文件权限;
    useEffect(() =>
    {
        const work = async() => {
            if(Platform.OS === 'android'){
                // if(!promptUpdate){
                requestPermissionFunction();
                await downloadAPKForInstall();
              }else if(Platform.OS === 'ios'){
              }
            // }
        };
        work();
    },[storagePermission]);

    const getSATPrice = async () => {
        try {
            console.log("获取价格");
            const lang = await AsyncStorage.getItem('@lang');
            setLang(lang as any);
            const ht = await getHotTokens();
            const p = ht.dict;
            const price = parseFloat(p.satprice);
            const usdtPrice = parseFloat(p.usdtprice);
            constansts.SATprice = price;
            constansts.USDTprice = usdtPrice;
            var MySat = 0;
            if (lang == 'zh')
                MySat = price * parseFloat(constansts.SATcount);
            else
                MySat = usdtPrice * parseFloat(constansts.SATcount);
            var MySatMoney = formartMoney(MySat.toString(), 4);
            setSATPrice(MySatMoney);

            var AllToken: any = constansts.Balance;
            var RmbPrice;
            var Proportion
            for (var j = 0; j < AllToken.tokens.length; j++) {
                if (AllToken.tokens[j].name == "USDT") {
                    Proportion = p.satprice / p.usdtprice
                    RmbPrice = parseFloat(AllToken.tokens[j].balance) * Proportion
                    AllToken.tokens[j].RmbPrice = RmbPrice;
                    AllToken.tokens[j].DollarPrice = AllToken.tokens[j].balance;
                    console.log(AllToken.tokens[j])
                } else {
                    AllToken.tokens[j].RmbPrice = "0.00";
                    AllToken.tokens[j].DollarPrice = "0.00";
                }
            }
            console.log("获取价格 SetBalance")
            constansts.Balance = AllToken;
            // console.log(AllToken)
        }catch (e) {
            console.log("获取价格:error ==> "+e)
        }finally {
            //排序按照美元金额，或者币量来决定
            constansts.Balance.tokens.sort((a:any,b:any)=>{
                let res =  Number(a.DollarPrice) < Number(b.DollarPrice) ;
                if(Number(b.DollarPrice) > 0 || Number(a.DollarPrice) > 0)
                {
                    return res;
                }
                else
                {
                    res = Number(a.balance) < Number(b.balance);
                    return res
                }
            })
            setBalances(constansts.Balance);
        }
    };

    //获取Android 读写SD权限;
    const requestPermissionFunction = async() =>
    {
        console.log('获取Android 读写SD权限');
        try {
            const permissions = [
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
            ];
            const granteds = await PermissionsAndroid.requestMultiple(permissions);
            if (granteds['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted') {
                setStoragePermission(true);
            } else {
                setStoragePermission(false);
                Alert.alert("请先开启权限！");
            }
            return storagePermission;
        } catch (err) {
            console.log("获取Android 读写SD权限:"+err);
        }
    }

    //TODO 更新下载
    const downloadAPKForInstall = async() => {
        if(storagePermission)
        {
            await marchAndDownloadingForInstall();
        }else{
            requestPermissionFunction();
        }
    };

    const safeSaveGlobalUrl = (data:any,type:any) => {
        let res;
        try {
            if(type === 0)
                res = JSON.parse(data);
            else
                res = data;
        }catch (e) {
            if(type===0)
                res = "http://198.245.49.104:5000";
            else
                res = ["http://198.245.49.104:5000/"];
        }
        return res;
    }

    //TODO 匹配本地appversion 并且 下载安装
    const marchAndDownloadingForInstall = async() => {
        console.log("匹配本地appversion 并且 下载安装")
        const newVersion = await getVersion(pkg.version,wallet.address);//原来getVersion

        //进行节点数据更新和合约数据获取
        constansts.nodeInfo = JSON.parse(newVersion.dict.node);
        constansts.contractListInfo = JSON.parse(newVersion.dict.contract);
        nodes.length=0;
        //修改节点数数据找这里
        nodes.push(["node_random",locale._("AutoSearch")])
        for(var i=0;i<constansts.nodeInfo.length;i++)
        {
            var list = [];
            list.push("node"+i);
            list.push("http://"+constansts.nodeInfo[i]+":5000")
            // list.push("http://"+"198.245.49.104"+":5001")
            nodes.push(list);
        }
        constansts.nodeUseful = JSON.parse(newVersion.dict.useful);
        constansts.FirstChatUrl = safeSaveGlobalUrl(newVersion.dict.firstcharturl,0);
        constansts.NormalChatUrlList = [...safeSaveGlobalUrl(newVersion.chaturl,1)];
        try {
            if (checkAppVersion(newVersion.dict.version, pkg.version)) {
                Alert.alert('', locale?._('checkNewversion'), [{
                    text: locale?._('cancel'),
                    onPress: () => console.log("Cancel Pressed"),
                    style: "cancel"
                }, {
                    text: locale?._('ok'),
                    onPress: async () => {
                        setModalVisible(true);
                        await downloadAPKFile(newVersion.dict.url);
                        setPromptUpdate(true);
                    }
                }]);
            }
        }catch (e) {
            console.log("checkAppVersionFalse ===>>>>"+e)
        }
        // }
    }

    //下载APK文件;
    const downloadAPKFile = async (dictUrl:any) =>
    {
        // const downloadAndroid = await RNFetchBlob.android
        // dictUrl = "http://106.75.144.161/down/SATApp-rel-3.3.1.apk";
        console.log('更新下载链接==》'+dictUrl)
        RNFetchBlob.config(
            {
                fileCache : true,
                // path: `${RNFetchBlob.fs.dirs.DownloadDir}/update.apk`,
                //   addAndroidDownloads : {
                //   useDownloadManager : true,
                //   title : 'smartx_app.apk',
                //   description : 'An APK that will be installed',
                //   mime : 'application/vnd.android.package-archive',
                //   path: `${RNFetchBlob.fs.dirs.DownloadDir}/smartx_app.apk`,
                //   mediaScannable : true,
                //   notification : true,
                // }
            })
            .fetch('GET', dictUrl, {
                // 'Accept': 'application/json',
                // 'Content-Type': 'application/json',
                // ... some headers,
                // 'Content-Type' : 'octet-stream'
            })
            .progress({count:100},(received: any, total: any) => {
                setProgressNumber((Math.round((received / total) * 100)));
                // Toast.show(Math.round(received / total*100).toString(),0.1)
                console.log(Math.round(received / total*100).toString())
            })

            // .then((res) => {
            //   downloadAndroid.actionViewIntent(res.path(), 'application/vnd.android.package-archive'), RNFetchBlob.fs.scanFile([{path:res.path(),mime:'apk'}])
            // })
            .then((res:any) => {
                setModalVisible(false);
                // downloadAndroid.actionViewIntent(res.path(), 'application/vnd.android.package-archive')
                RNApkInstallerN.install(res.path());
            })
            .catch((err:any)=>{
                setModalVisible(false);
                Toast.show("请重新点击")
                console.log('downloadAPKForInstall err: ' + err);
            });
    }

    //检查是否有新的版本;
    const checkAppVersion = (serverVersionCode:any,localVersionCode:any) => {
        try{
            const currentVersionCode = formatVersionCode(localVersionCode);
            const newsVersionCode = formatVersionCode(serverVersionCode);
            //console.log('checkAppVersion  localVersionCode: ' + currentVersionCode + ' newsVersionCode: ' + newsVersionCode);
            if(parseInt(currentVersionCode) < parseInt(newsVersionCode)){
                return true;
            }
        }catch(error){
            console.log(error);
        }
        return false;
    }

    //TODO  格式化VersionCode
    const formatVersionCode = (versionCode:any)=>{
        return versionCode.replace('.','').replace('.','');
    }

    const onCopy = () => {
        Clipboard.setString(wallet.address);
        Toast.show(locale?._('copied') as string);
    };

    const getClipboardString = async () => {
        const content = await Clipboard.getString();
        return content;
    }

    const RedEnvelopeLoadBack =  (res: any) => {
        setShowRedEnvelopeLoad(false);
        //console.log(res)
        if (res == "0") {
        } else if (res == "1") {
            playSound("openred.mp3");
            GetRedEnvelope(wallet.address, pkgid).then(
                async ()=>{

                    //console.log(`openRedEnvelopeConAddress=${openRedEnvelopeConAddress}`)
                    if(openRedEnvelopeConAddress !== "")
                    {
                        for(var i=0;i<(constansts.addTokens).length;i++)
                        {
                            //如果有相同的就只接跳出
                            if( (constansts.addTokens[i] as any).address===openRedEnvelopeConAddress)
                            {
                                break;
                            }
                            //到最后一个并且不相同 添加再退出
                            if((constansts.addTokens[i] as any).address!==openRedEnvelopeConAddress && i === ((constansts.addTokens).length - 1))
                            {
                                (constansts.addTokens as any).push({address:openRedEnvelopeConAddress,url:openRedEnvelopeUrl,desc:openRedEnvelopeTokenName});
                                //console.log(`添加后的代币列表:${JSON.stringify(constansts.addTokens)}`)
                                await AsyncStorage.setItem('@addTokens',JSON.stringify(constansts.addTokens as any));
                                break;
                            }
                        }
                        if((constansts.addTokens).length === 0 )
                        {
                            (constansts.addTokens as any).push({address:openRedEnvelopeConAddress,url:openRedEnvelopeUrl,desc:openRedEnvelopeTokenName});
                            //console.log(`添加后的代币列表:${JSON.stringify(constansts.addTokens)}`)
                            await AsyncStorage.setItem('@addTokens',JSON.stringify(constansts.addTokens as any));
                        }

                    }

                    navigation.navigate('RedEnvelopeInfo', { pkgid: pkgid});
                    await addRedEnvelopeGet(pkgid);
                }

            );

        } else if (res == "2") {
            navigation.navigate('RedEnvelopeInfo', { pkgid: pkgid});
        }
    }

    const playSound = (name:string) => {
        Sound.setCategory('Playback') // 在静音模式下启用播放'
        let whoosh = new Sound(name, Sound.MAIN_BUNDLE, (error) => {
            whoosh.play((success) => {
                whoosh.release()
            })
        })
    }

    // @ts-ignore
    return (
        <View>
            <Modal animationType='fade' statusBarTranslucent={true} transparent={true} visible={modalVisible} onRequestClose={()=>{
                  setModalVisible(!modalVisible);
                  // Alert.alert("Modal has been closed.");
                }}>
                <View style={styles.progressBarView}>
                    <View style={styles.subView}>
                        <Text style={styles.title}>
                            {locale?._('isDownLoad')}
                        </Text>
                        <ProgressBar
                          color="black"
                          styleAttr="Horizontal"
                          indeterminate={false}
                          progress={
                            progressNumber / 100
                            } />
                        <View style = { styles.progressContainer }>
                            <Text style = { styles.progressLeftText }>
                                {
                                  progressNumber
                                }%
                            </Text>
                            <Text style={styles.progressRightText}>
                              {
                                  100
                              }%
                            </Text>
                        </View>
                        {/* {needCancle &&
                            <View style = { styles.cancleContainer } >
                                <TouchableOpacity style = { styles.cancleButton } onPress = { canclePress } >
                                    <Text style = { styles.cancleText } >
                                        { cancleText }
                                    </Text>
                                </TouchableOpacity>
                            </View>
                        } */}
                    </View>
                </View>
            </Modal>
            {
                showGift?
                    <View style={{height:height,width:width}}>
                        {
                            // @ts-ignore
                            <WebBrowser url={Gifturl} address={wallet.address} showExplore={false} title={'活动'} navigation={navigation} locale={locale} wallet={wallet}/>
                        }
                    </View>:null
            }
            <View style={{backgroundColor: '#FAFBFDFF', paddingBottom: 10}}>
                <View style={{
                    flexDirection: 'row',
                    alignItems: 'baseline',
                    marginTop: Platform.OS === 'ios' ? 40:20,
                    marginHorizontal: 20
                }}>
                    <View style={{alignItems: 'center'}}>
                        <Text
                            style={{fontSize: 18, fontWeight: 'bold', color: '#7259E0FF'}}
                        >{locale?._('Assets.wallet')}</Text>
                    </View>
                    <TouchableOpacity  style={{marginLeft: 14}} onPress={
                        async () => {
                            let firstChat: string | null = "";
                            try {
                                firstChat = await AsyncStorage.getItem("FirstInMiChat")
                            }catch (e) {

                            }
                            //console.log(firstChat)
                            // if(firstChat === "" || firstChat === null)
                            // {
                            //     navigation.push("ChatFirstSet")
                            // }
                            // else
                            navigation.push("ChatListTemp");
                        }}>
                        <Text style={{fontSize: 16}}>{locale?._('Tabs.chat')}</Text>
                    </TouchableOpacity>
                    {/*<TouchableOpacity  style={{marginLeft: 14}} onPress={*/}
                    {/*    async () => {*/}
                    {/*        navigation.push("ChatGroupMy");*/}
                    {/*    }}>*/}
                    {/*    <Text style={{fontSize: 16}}>{locale?._('Tabs.group')}</Text>*/}
                    {/*</TouchableOpacity>*/}
                    <View style={{flex: 1}}/>
                    <TouchableOpacity onPress={()=>{
                        // setShowGift(true)
                        // navigation.navigate('WebBrowserInfo',{url:"http://106.75.144.161/?address="+wallet.address+"&InitToGroupChatView=true",showExplore:false,title:"Orca exchange",headerShownFalse:false})
                        navigation.navigate('WebBrowserInfo',{url:"http://106.75.144.161:3661/?address="+wallet.address+"&InitToGroupChatView=true",showExplore:false,title:"Group",headerShownFalse:false})
                        // navigation.navigate('WebBrowserInfo',{url:"http://192.168.1.104:8181/?address="+wallet.address+"&InitToGroupChatView=true",showExplore:false,title:"Group",headerShownFalse:false})
                        // navigation.navigate('WebBrowserInfo',{url:"http://func2.smartx.one/?address="+wallet.address+"&InitToGroupChatView=true",showExplore:false,title:"Orca exchange",headerShownFalse:false})
                    }
                    }>
                        <Icon type='font-awesome' name='commenting-o' color={"rgb(114, 89, 224)"} style={{width: 24, height: 24}}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => navigation.navigate(('Scan'), {coin: "SAT", tokenAddress: ""})}
                                      style={{marginLeft: 14}}>
                        <ImageBackground source={scan} style={{width: 24, height: 24}}/>
                    </TouchableOpacity>
                </View>
            </View>

            <ScrollView disableScrollViewPanResponder={true} nestedScrollEnabled={false} refreshControl={
                <RefreshControl refreshing={false} onRefresh={() => setRefresh(true)} collapsable={true}/>
            }>
                <View style={{backgroundColor: '#F7FBFE', paddingBottom: 24}}>
                    <ImageBackground source={balanceBG} style={{
                        height: 130,
                        paddingLeft: 20,
                        alignItems: 'flex-start',
                        margin: 18,
                        marginBottom: 5
                    }} imageStyle={{borderRadius: 10}}>
                        <Text style={{color: 'white', fontSize: 12,marginTop:"4%"}}>{locale?._('Assets.balance')}</Text>
                        <View style={{width:"100%",marginTop:"1%",flexDirection:"row"}}>
                            {/*总资产以及汇率显示*/}
                            <Text style={{color: 'white', fontSize: 28 }}>{formartMoney(AllSAT, 4)}</Text>
                            {
                                lang=='zh'?
                                    <Text style={{color: 'white', fontSize: 12,textAlignVertical:"bottom" }}>  ≈¥{AllSATPrice}</Text>
                                    :
                                    <Text style={{color: 'white', fontSize: 12,textAlignVertical:"bottom" }}>  ≈${AllSATPrice}</Text>
                            }
                        </View>
                        <View style={{width:"100%",marginTop:"2%"}}>
                            <Text style={{color: 'white', fontSize: 12 }}>{locale?._('Assets.send.balance')} {formartMoney(balances.SAT,4)} 丨{locale?._('Assets.send.pledge')} {formartMoney(HYSAT, 4)} </Text>
                        </View>
                        <TouchableOpacity onPress={onCopy}  >
                            <View style={{flexDirection:"row",flex:1,marginTop:"2.7%",width:"100%",justifyContent:"flex-end",paddingRight:"5%"}}>
                                <Text style={{color: 'white', fontSize: 13}}>{wallet.address.slice(0,13)}...{wallet.address.slice(-13)}</Text>
                                <ImageBackground source={copyImg}  style={{width:12,height:18,marginLeft:5}}/>
                            </View>
                        </TouchableOpacity>

                    </ImageBackground>
                    <View style={{width:width,height:23}}>
                        {/*<Swiper style={styles.wrapper} autoplayDirection={true} horizontal={false} showsButtons={false} autoplay loop autoplayTimeout={3} showsPagination={false}>*/}
                        {/*    {*/}
                        {/*        console.log("公告数量"+Announce.length)*/}
                        {/*    }*/}
                        {/*    {*/}
                        {/*        // Announce.map((item:any,index:any)=>{*/}
                        {/*        //     <View key={index} style={styles.slide1}>*/}
                        {/*        //         <Text style={styles.text}>🔈{item}</Text>*/}
                        {/*        //     </View>*/}
                        {/*        // })*/}
                        {/*    }*/}
                        {/*         <View  style={styles.slide1}>*/}
                        {/*             <Text style={styles.text}>🔈{Announce[0]}</Text>*/}
                        {/*         </View>*/}
                        {/*        <View  style={styles.slide1}>*/}
                        {/*            <Text style={styles.text}>🔈{Announce[1]}</Text>*/}
                        {/*        </View>*/}
                        {/*        <View  style={styles.slide1}>*/}
                        {/*            <Text style={styles.text}>🔈{Announce[2]}</Text>*/}
                        {/*        </View>*/}
                        {/*        <View  style={styles.slide1}>*/}
                        {/*            <Text style={styles.text}>🔈{Announce[3]}</Text>*/}
                        {/*        </View>*/}
                        {/*        <View  style={styles.slide1}>*/}
                        {/*            <Text style={styles.text}>🔈{Announce[4]}</Text>*/}
                        {/*        </View>*/}
                        {/*</Swiper>*/}
                    </View>
                    <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
                        <TouchableOpacity onPress={() => navigation.navigate('Receive')} style={{alignItems: 'center'}}>
                            <ImageBackground source={receive} style={{width: 30, height: 30}}/>
                            <Text style={{fontSize: NFTView_TitleSize, marginTop: 4}}>{locale?._('Assets.receive')}</Text>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => navigation.push('Send', {coin:"SAT", tokenAddress:""})}
                                          style={{alignItems: 'center'}}>
                            <ImageBackground source={send} style={{width: 30, height: 30}}/>
                            <Text style={{fontSize: NFTView_TitleSize, marginTop: 4}}>{locale?._('Assets.send')}</Text>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => navigation.navigate('Txs')} style={{alignItems: 'center'}}>
                            <ImageBackground source={txs} style={{width: 30, height: 30}}/>
                            <Text style={{fontSize: NFTView_TitleSize, marginTop: 4}}>{locale?._('Assets.txs')}</Text>
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={{flexDirection: 'row', margin: 14}}>
                    {/*<Text style={{fontSize: 18, fontWeight: 'bold', marginLeft: 7}}>{locale?._('Tabs.assets')}</Text>*/}
                    <View style={{width:120,alignItems:"flex-start"}}>
                        <Tab value={Asset_Index} variant={'default'} onChange={(i)=>setAsset_Index(i)} disableIndicator={false}
                             indicatorStyle={{
                                 height:2,
                                 backgroundColor:"black",
                                 width:20,
                                 left:20
                             }}
                        >
                            <Tab.Item title={locale._("Tabs.assets")}
                                      background={null}
                                      buttonStyle={{padding:0,margin:0}}
                                      containerStyle={{backgroundColor:"white"}}
                                      titleProps={{style:{padding:0,color:"black",fontSize:NFTView_TitleSize,lineHeight:NFTView_TitleSize*2,}}}
                                      />
                            <Tab.Item title="NFT"
                                      background={null}
                                      buttonStyle={{padding:0,margin:0}}
                                      containerStyle={{backgroundColor:"white"}}
                                      // borderBottomWidth:Asset_Index==1?2:0
                                      titleProps={{style:{padding:0,color:"black",fontSize:NFTView_TitleSize,lineHeight:NFTView_TitleSize*2,}}}
                                      />
                        </Tab>
                    </View>
                    <View style={{flex: 1}}/>
                    <TouchableOpacity onPress={() => {
                        if(Asset_Index===0)
                        {
                            navigation.push('GetTokens')
                        }
                        else
                        {
                            navigation.push('NFTAddContract')
                        }
                    }}>
                        <Icon type='feather' name='plus-circle' color='#7259E0FF' size={24} />
                    </TouchableOpacity>
                </View>
                <TabView value={Asset_Index} >
                    <TabView.Item style={{width: '100%' }}>
                        <View>
                            {
                                [{name: 'SAT', balance: balances.SAT}, ...balances.tokens].map((item:any,index) => (
                                    <ListItem bottomDivider key={index}
                                              onLongPress={()=>{
                                                  if(item.name==="SAT")
                                                  {
                                                      return;
                                                  }
                                                  Alert.alert("",locale?._('Assets.confirmDelete')+(item as any).desc+" ?",[{
                                                      text: locale?._('cancel'),
                                                      onPress: () => console.log("Cancel Pressed"),
                                                      style: "cancel"
                                                  }, {
                                                      text: locale?._('confirm'),
                                                      onPress: async () => {
                                                          for(var i=0;i<(constansts.addTokens).length;i++)
                                                          {
                                                              if((constansts.addTokens[i] as any).address==(item as any).address)
                                                              {
                                                                  (constansts.addTokens as any).splice(i,1);
                                                                  break;
                                                              }
                                                          }
                                                          await AsyncStorage.setItem('@addTokens',JSON.stringify(constansts.addTokens as any));
                                                          setRefresh(true)
                                                      }
                                                  }])}
                                              }
                                              onPress={() => navigation.push(('PreSend'), {
                                                  coin: ((item.name == "SAT" || item.name == "sETH" || item.name == "sUSDT") ? item.name : (item as any).desc),
                                                  tokenAddress: (item as any).address,
                                                  item:item
                                              })}>
                                        {
                                            item.name === 'SAT' ?
                                                <Avatar source={logo} activeOpacity={0.7} iconStyle={{}}/>
                                                :
                                                (
                                                    (item as any).address === constansts.contractAddressImage.sUSDT ?
                                                        <Avatar source={require('./../assets/susdt.png')} activeOpacity={0.7}/>
                                                        :
                                                        (
                                                            (item as any).address === constansts.contractAddressImage.sETH?
                                                                <Avatar source={require('./../assets/1.png')}
                                                                        activeOpacity={0.7}/>
                                                                :
                                                                (
                                                                    (item as any).url == "" ?
                                                                        <Avatar source={require('./../assets/hotTokenLogo.png')}
                                                                                activeOpacity={0.7}/>
                                                                        :
                                                                        <Avatar source={{uri: (item as any).url}}
                                                                                activeOpacity={0.7}/>
                                                                )
                                                        )
                                                )
                                        }
                                        <ListItem.Content>
                                            {
                                                item.name === 'SAT' ?
                                                    <ListItem.Title style={{fontSize: NFTView_TitleSize}}>{(item as any).name}</ListItem.Title>
                                                    :
                                                    (
                                                        (item as any).address === constansts.contractAddressImage.sUSDT ?
                                                            <ListItem.Title
                                                                style={{fontSize: NFTView_TitleSize}}>{(item as any).name}</ListItem.Title>
                                                            :
                                                            (
                                                                (item as any).address === constansts.contractAddressImage.sETH ?
                                                                    <ListItem.Title
                                                                        style={{fontSize: NFTView_TitleSize}}>{(item as any).name}</ListItem.Title>
                                                                    :
                                                                    <ListItem.Title
                                                                        style={{fontSize: NFTView_TitleSize}}>{(item as any).desc}</ListItem.Title>
                                                            )

                                                    )
                                            }

                                        </ListItem.Content>
                                        {/*币种右下角比例显示*/}
                                        <View style={{alignItems: 'flex-end'}}>
                                            <Text style={{
                                                fontSize: 17,
                                                fontWeight: 'bold'
                                            }}>{formartMoney(item.balance, 4)}</Text>
                                            {
                                                item.name === 'SAT' ?

                                                    (
                                                        lang=='zh'?
                                                            <Text style={{fontSize: 12, color: '#999999FF'}}>≈ ¥{SATprice}</Text>
                                                            :
                                                            <Text style={{fontSize: 12, color: '#999999FF'}}>≈ ${SATprice}</Text>
                                                    )
                                                    :
                                                    (
                                                        lang=='zh'?
                                                            <Text style={{fontSize: 12, color: '#999999FF'}}>≈ ¥{formartMoney(item.RmbPrice, 4)}</Text>
                                                            :
                                                            <Text style={{fontSize: 12, color: '#999999FF'}}>≈ ${formartMoney(item.DollarPrice,4)}</Text>
                                                    )

                                            }
                                        </View>
                                    </ListItem>
                                ))
                            }
                        </View>
                    </TabView.Item>
                    <TabView.Item style={{ width: '100%' ,minHeight:100}}>
                        <View>
                        {
                            NFTContracts.length>0?
                            NFTContracts.map((item:any,index:number)=>(
                                <ListItem onPress={()=>{
                                    console.log(index)
                                    navigation.push('NFTContract',{item:item})
                                }} bottomDivider key={index+"_NFT"} >
                                    {
                                        item.contract==="c3MbYezD7CV9KcRZbnoVTmT6SMAzs2REL"?
                                            <Avatar source={SmartXLogo} rounded={true} activeOpacity={0.7}/>
                                            :
                                            <Avatar title={item.name.slice(0,2)} containerStyle={{backgroundColor:"lightgrey"}} rounded={true} activeOpacity={0.7}/>
                                    }

                                    <ListItem.Content >
                                        <ListItem.Title style={{fontSize: NFTView_TitleSize}}>{item.name}</ListItem.Title>
                                    </ListItem.Content>
                                    <ListItem.Title>
                                        {item.myNFTS.length}
                                    </ListItem.Title>
                                </ListItem>
                                ))
                                :
                                <Image
                                    PlaceholderContent={<ActivityIndicator />}
                                    style={{width:width,height:300}}
                                    source={NFT}/>
                        }
                        </View>
                    </TabView.Item>
                </TabView>
                <View
                    style={{height: (height - (height / 9.5) * (balances.tokens.length) - height * 0.256) > height * 0.2 ? (height - (height / 9.5) * (balances.tokens.length) - height * 0.256) : height * 0.2}}>
                </View>
            </ScrollView>
            {/*<RedEnvelopeLoad visible={showRedEnvelopeLoad} back={RedEnvelopeLoadBack}/>*/}
            <RedEnvelopeLoad visible={showRedEnvelopeLoad} back={RedEnvelopeLoadBack} sender={sender} loadType={loadType} bless={coverTxt}/>
        </View>
    );
};

const styles = StyleSheet.create({
  progressBarView: {
      flex:1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: 'rgba(0,0,0,0.2)',
  },
  barStyle: {
      marginLeft: 10,
      marginRight: 10,
      width:width - 80
  },
  progressLeftText: {
      fontSize: 14
  },
  cancleContainer: {
      justifyContent: 'center',
      alignItems: 'flex-end'
  },
  progressRightText: {
      fontSize: 14,
      color: '#666666'
  },
  barBackgroundStyle: {
      backgroundColor: '#cccccc'
  },
  progressContainer: {
      flexDirection: 'row',
      padding: 10,
      justifyContent: 'space-between'
  },
  subView: {
      marginLeft: 30,
      marginRight: 30,
      paddingLeft:10,
      paddingRight:10,
      backgroundColor: '#fff',
      alignSelf: 'stretch',
      justifyContent: 'center',
      borderRadius:20,
  },
  progressView: {
      flexDirection: 'row',
      padding: 10,
      paddingBottom: 5,
      justifyContent: 'space-between'
  },
  title: {
      textAlign: 'left',
      padding:10,
      fontSize: 16
  },
  cancleButton: {
      padding:10
  },
  cancleText: {
      textAlign: 'right',
      paddingTop: 0,
      fontSize: 16,
      color: 'rgba(0, 122, 255, 1)'
  },
    wrapper: {
    },
    slide1: {
        flex: 1,
        justifyContent: 'center',
        alignItems: "flex-start",
        // backgroundColor: '#fff',
        marginLeft:width*0.05

    },
    slide2: {
        flex: 1,
        justifyContent: 'center',
        alignItems: "flex-start",
        // backgroundColor: '#fff',
        marginLeft:width*0.05
    },
    slide3: {
        flex: 1,
        justifyContent: 'center',
        alignItems: "flex-start",
        // backgroundColor: '#fff',
        marginLeft:width*0.05
    },
    text: {
        color: 'blue',
        fontSize: height*0.018,
        lineHeight:height*0.02,
        fontWeight: 'bold'
    }
});

export default Home;

